<script setup>
import { onMounted, ref, reactive } from "vue";
import mangocrud from "@/components/magnxo_crud/index.vue";
import msggage from "@/utils/ActionMessage.js";
import AMapLoader from "@amap/amap-jsapi-loader";
const props = defineProps({
  modelRef: Object,
  keyword: String,
  temporary: Object,
});
const emit = defineEmits(["setKeyword","settemporary"]);
let map = reactive(null);
let refAMap = reactive(null);
let MouseToola = reactive(null);
let polyEditora = reactive(null);
let modelRef = reactive(props.modelRef);
const handlerail = () => {
  map.plugin(["AMap.MouseTool"], function () {
    MouseToola = new refAMap.MouseTool(map);
    map.addControl(MouseToola);
  });
  //   mouseTool = new refAMap.MouseTool(map);
  const polygon = MouseToola.polygon({
    strokeColor: "#1791fc",
    strokeOpacity: 1,
    fillColor: "#1791fc",
    fillOpacity: 0.5,
    // strokeStyle还支持 solid
    strokeStyle: "solid",
    draggable: true,
    // lineJoin: "bevel",
    strokeWeight: 1,
    cursor: "ani",
    lineJoin: "round",
    // strokeDasharray: [30,10],
  });
  MouseToola.on("draw", function (event) {
    // event.obj 为绘制出来的覆盖物对象
     emit('settemporary',[])
    var polygonItem = event.obj;
    var paths = polygonItem.getPath(); //取得绘制的多边形的每一个点坐标
    var path = []; // 编辑的路径
    paths.forEach((v) => {
      path.push([v.lng, v.lat]);
    });
  emit('settemporary',path)
    editRectangle(path);
    map.remove(event.obj); // 删除多边形
  });
};
const editRectangle = (paths) => {
  debugger
  map.clearMap();
  const path = paths;
  let AMap = refAMap;
  let polygon = new refAMap.Polygon({
    path: path,
    strokeColor: "#1791fc", //线条颜色
    strokeWeight: 1,
    borderWeight: 1, //线条宽度
    strokeOpacity: 1, //0.2
    fillOpacity: 0.35, //0.4
    fillColor: "#1791fc", //多边形填充颜色
    zIndex: 50,
  });
  map.add(polygon);
  map.setFitView([polygon]);
  debugger;
  polyEditora = new AMap.PolyEditor(map, polygon);
  polyEditora.open();
   emit('settemporary',polygon.getPath())
  polyEditora.on("addnode", function (event) {
    console.info("触发事件：addnode", event);
    console.info("修改后的经纬度：", polygon.getPath());
   emit('settemporary',polygon.getPath())

  });

  polyEditora.on("adjust", function (event) {
    console.info("触发事件：adjust", event);
    console.info("修改后的经纬度：", polygon.getPath());
   emit('settemporary',polygon.getPath())

  });

  polyEditora.on("removenode", function (event) {
    console.info("触发事件：removenode", event);
    console.info("修改后的经纬度：", polygon.getPath());
   emit('settemporary',polygon.getPath())

  });

  polyEditora.on("end", function (event) {
    console.info("触发事件： end", event);
    console.info("修改后的经纬度：", polygon.getPath());
   emit('settemporary',polygon.getPath())

    // event.target 即为编辑后的多边形对象
  });
};
const init = () => {
  return new Promise((res, rej) => {
    debugger
    let lnglatXY = ["", ""]; //已知点坐标 cf963b49585bead02bf9518f850feaf7
    AMapLoader.load({
      key: "3a997f5794eaabdda9dbcd8d507e64e3", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugin: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      AMapUI: {
        // 是否加载 AMapUI，缺省不加载
        version: "1.1", // AMapUI 缺省 1.1
        plugins: [], // 需要加载的 AMapUI ui插件
      },
      Loca: {
        // 是否加载 Loca， 缺省不加载
        version: "1.3.2", // Loca 版本，缺省 1.3.2
      },
    })
      .then((AMap) => {
        refAMap = AMap;
        let mapxylist = [modelRef.lat, modelRef.lng]; //下面绘制地图不支持直接将this放进去
        map = new AMap.Map("container", {
          resizeEnable: true,
          zoom: 13,
          center: mapxylist, //回显数据
        });
        map.plugin("AMap.Geolocation", function () {
          //浏览器定位
          // var geolocation = new AMap.Geolocation({
          //   enableHighAccuracy: true, //是否使用高精度定位，默认:true
          //   timeout: 15000, //超过10秒后停止定位，默认：无穷大
          //   maximumAge: 5000, //浏览器原生定位的缓存时间 定位结果缓存0毫秒，默认：0
          //   convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          //   showButton: true, //显示定位按钮，默认：true
          //   buttonPosition: "LB", //定位按钮停靠位置，默认：'LB'，左下角
          //   buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          //   showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          //   showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          //   panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          //   zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          // });
          // map.addControl(geolocation); //添加控件,可以是任何插件对象
          // geolocation.getCurrentPosition(); //获取用户当前的精确位置信息
          
        });
        map.plugin(["AMap.Geocoder"], function () {
          map.addControl(new AMap.Geocoder());
        });
        map.plugin(["AMap.PolyEditor"], function () {
          map.addControl(new AMap.PolyEditor());
        });

        // 启用工具条
        map.plugin(["AMap.ToolBar"], function () {
          map.addControl(new AMap.ToolBar());
        });
        let autoOptions = "";
        let geocoder = null;
        let placeSearch = null;
        AMap.service("AMap.PlaceSearch", function () {
          placeSearch = new AMap.PlaceSearch({
            // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
            city: "010",
          });

          placeSearch.search("北京大学", function (status, result) {
            console.log(status, result);
            // 查询成功时，result即对应匹配的POI信息
          });
          AMap.plugin("AMap.Autocomplete", () => {
            autoOptions = {
              input: "addressInput", // 输入框ID
            };
          });
          geocoder = new AMap.Geocoder({
            city: "010", //城市设为北京，默认：“全国”
            radius: 1000, //范围，默认：500
          });
        });
        let auto = new AMap.Autocomplete(autoOptions);

        AMap.event.addListener(auto, "select", select); //注册监听，当选中某条记录时会触发
        let infoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(0, -30),
        });

        function select(e) {
          placeSearch.setCity(e.poi.adcode);
          if (e.poi && e.poi.location) {
            map.setZoom(15);
            map.setCenter(e.poi.location);
          }
          placeSearch.search(e.poi.name, function (status, result) {
            if (status === "complete" && result.info === "OK") {
              for (let h = 0; h < result.poiList.pois.length; h++) {
                //返回搜索列表循环绑定marker
                let jy = result.poiList.pois[h]["location"]; //经纬度
                let address = result.poiList.pois[h]["address"]; //地址
                if (marker) {
                  marker.setMap(null);
                  marker = null;
                }
                marker = new AMap.Marker({
                  //加点
                  map: map,
                  position: jy,
                });
                marker.extData = {
                  getLng: jy["lng"],
                  getLat: jy["lat"],
                  address: address,
                }; //自定义想传入的参数
                marker.content = "123123123";
                marker.on("click", function (e) {
                  let hs = e.target.extData;
                  infoWindow.setContent(hs["address"]); //点击以后窗口展示的内容
                  infoWindow.open(map, e.target.getPosition());
                  modelRef.lat = hs.getLng;
                  modelRef.lng = hs.getLat;
                  emit('setKeyword',hs.address)
                });
                marker.emit("click", { target: marker });
              }
            }
          }); //关键字查询查询
        }

        // 默认点
        let marker = new AMap.Marker({
          //加点
          map: map,
        });
        map.on("click", function (e) {
          if (marker) {
            marker.setMap(null);
            marker = null;
          }
          let getLng = e.lnglat.getLng();
          let getLat = e.lnglat.getLat();
          lnglatXY = [getLng, getLat]; //已知点坐标
          modelRef.lat = getLng;
          modelRef.lng = getLat;
          marker = new AMap.Marker({
            //加点
            map: map,
            position: lnglatXY,
          });
          geocoder.getAddress(lnglatXY, function (status, result) {
            if (status === "complete" && result.regeocode) {
              var address = result.regeocode.formattedAddress;
             emit('setKeyword',address)
            } else {
              // log.error('根据经纬度查询地址失败')
            }
          });
        });
        res();
      })
      .catch((e) => {
        console.log(e);
        console.log("地图加载失败");
        rej();
      });
  });
};
defineExpose({
  init,
  handlerail,
  editRectangle
});
</script>
<template>
      <div class="gaodedia">
          <div class="coord_map">
        <div id="container" class="amap-container"></div>
        <div id="tip">
          <b>请输入关键字：</b>
          <input
            type="text"
            id="addressInput"
            autocomplete="off"
            name="keyword"
            style="width: 95%"
            v-model="props.keyword"
          />
          <div id="result1" name="result1" style="display: none"></div>
        </div>
        <div id="pos">
          <b>鼠标左键在地图上单击获取坐标</b>
          <br />
          <div>
            经度：
            <input
              type="text"
              id="resultLng"
              name="park_logitue"
              disabled
              v-model="modelRef.lat"
              autocomplete="off"
            />
            &nbsp;纬度：
            <input
              autocomplete="off"
              type="text"
              id="resultLat"
              name="park_latutide"
              disabled
              v-model="modelRef.lng"
            />
            <span class="error10"></span>
          </div>
                   <b>鼠标左键在地图上单击获取坐标</b>
        </div>
      </div>
      </div>
</template>
<style lang="scss">
.gaodedia {
  // 下面是高德样式
  .coord_map {
    position: relative;
    left: 50%;
    z-index: 0;
    float: left;
    width: 100%;
    height: 380px;
    overflow: hidden;
    background: #efefef;
    border: 1px solid #e0e0e0;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    transform: translateX(-50%);
  }

  .amap-container {
    width: 100%;
    height: 100%;
  }

  .coord_map .search {
    position: absolute;
    top: 12px;
    right: 20px;
    z-index: 99999;
    width: 300px;
    height: 40px;
  }

  .coord_map .search .text_3 {
    position: relative;
    float: left;
    width: 220px;
    height: 32px;
    height: /*\**/ 26px \9;
    padding: 0 0 0 10px;
    padding: /*\**/ 6px 0 0 10px \9;
    color: #666666;
    font-size: 15px;
    font-family: "Microsoft YaHei", arial, sans-serif;
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 0px;
    -webkit-transition: all 0.2s linear 0s;
    -moz-transition: all 0.2s linear 0s;
    -o-transition: all 0.2s linear 0s;
    transition: all 0.2s linear 0s;
    /* behavior: url(css/pie2.htc); */
  }

  .coord_map .search .text_3:hover {
    border: 1px solid #ffc98d;
  }

  .coord_map .search .text_3:focus {
    border: 1px solid #ffc98d;
    box-shadow: 0 0 4px rgba(255, 201, 141, 0.6);
  }

  .coord_map .search .btn_search {
    position: relative;
    float: left;
    width: 60px;
    height: 34px;
    margin: 0px 0px 0;
    color: #fff;
    font-weight: normal;
    font-size: 15px;
    font-family: "Microsoft YaHei", arial, sans-serif;
    text-indent: -9999px;
    /* background: #ffa33b url(../images/search_ico.png) no-repeat 20px 8px; */
    border: none;
    border-radius: 0 3px 3px 0;
    cursor: pointer;
    filter: none;
    -webkit-transition: all 0.1s linear 0s;
    -moz-transition: all 0.1s linear 0s;
    -o-transition: all 0.1s linear 0s;
    transition: all 0.1s linear 0s;
    /* behavior: url(css/pie2.htc); */
  }

  .coord_map .search #search_list {
    position: absolute;
    top: 34px;
    left: 0px;
    z-index: 9999;
    display: none;
    width: 230px;
    min-height: 33px;
    max-height: 264px;
    overflow-x: hidden;
    overflow-y: auto;
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 2px;
    box-shadow: 1px 1px 1px 0 #e0e0e0;
  }

  .coord_map .search #search_list li {
    width: 100%;
    height: 33px;
    color: #666;
    font-size: 12px;
    line-height: 33px;
    text-indent: 7px;
    cursor: pointer;
    -webkit-transition: all 0.2s linear 0s;
    -moz-transition: all 0.2s linear 0s;
    -o-transition: all 0.2s linear 0s;
    transition: all 0.2s linear 0s;
  }

  .coord_map .search #search_list li:nth-of-type(even) {
    background: #f9f9f9;
  }

  .coord_map .search #search_list li:hover {
    color: #444;
    background: #fdfcd7;
  }

  .coord_map .search #search_list li:last-child {
    border-bottom: 0px solid #efefef;
  }

  .coord_map .coordinate {
    position: absolute;
    top: 70px;
    z-index: 99999;
    width: 243px;
    height: 170px;
    /* background: url(../images/coordinate_bg.png) no-repeat; */
  }

  .coord_map .coordinate .name {
    position: relative;
    width: 100%;
    height: 46px;
    margin: 0 auto 15px;
    font-size: 14px;
    line-height: 46px;
    text-indent: 12px;
  }

  .coord_map .coordinate .name .ico {
    position: absolute;
    top: 4px;
    left: 100px;
    display: inline-block;
    width: 29px;
    height: 35px;
    /* background: url(../images/mapStart_01.png) no-repeat; */
  }

  .coord_map .coordinate .content {
    width: 100%;
    height: 100px;
  }

  .coord_map .coordinate .content .cure_1 {
    float: left;
    margin: 5px 5px 0 17px;
  }

  .coord_map .coordinate .content .cure_2 {
    float: left;
    margin: 5px 5px 0 10px;
  }

  .coord_map .coordinate .content .text_0 {
    float: left;
    width: 52px;
    height: 31px;
    font-size: 15px;
    text-align: center;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    -webkit-transition: all 0.2s linear 0s;
    -moz-transition: all 0.2s linear 0s;
    -o-transition: all 0.2s linear 0s;
    transition: all 0.2s linear 0s;
  }

  .coord_map .coordinate .content .text_0:hover {
    border: 1px solid #ffc98d;
  }

  .coord_map .coordinate .content .text_0:focus {
    border: 1px solid #ffc98d;
    box-shadow: 0 0 4px rgba(255, 201, 141, 0.6);
  }

  .coord_map .coordinate .content .text_00 {
    float: left;
    width: 52px;
    height: 31px;
    font-size: 15px;
    text-align: center;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    -webkit-transition: all 0.2s linear 0s;
    -moz-transition: all 0.2s linear 0s;
    -o-transition: all 0.2s linear 0s;
    transition: all 0.2s linear 0s;
  }

  .coord_map .coordinate .content .btn_biao {
    position: relative;
    width: 171px;
    height: 32px;
    margin: 11px 0px 0;
    margin: 15px 0 0 50px;
    color: #fff;
    font-weight: normal;
    font-size: 15px;
    font-family: "Microsoft YaHei", arial, sans-serif;
    background: #ffa33b;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    filter: none;
    -webkit-transition: all 0.1s linear 0s;
    -moz-transition: all 0.1s linear 0s;
    -o-transition: all 0.1s linear 0s;
    transition: all 0.1s linear 0s;
    /* behavior: url(css/pie2.htc); */
  }

  .coord_map .map {
    position: absolute;
    z-index: 9;
    width: 720px;
    height: 380px;
  }

  .coord_map .tco {
    display: block;
    margin: 40px auto 0;
  }

  #nav {
    float: left;
    width: 300px;
    height: 363px;
    padding: 5px;
    line-height: 35px;
    background-color: #eee;
  }

  #section {
    float: left;
    width: 600px;
    padding: 10px;
  }

  #mapContainer {
    position: absolute;
    top: 28px;
    right: 7px;
    bottom: 44px;
    left: 315px;
  }

  #tip {
    position: absolute;
    top: 0px;
    right: 0px;
    /*min-width: 400px;*/
    min-height: 65px;
    padding-right: 2px;
    padding-left: 10px;
    overflow: hidden;
    font-size: 12px;
    line-height: 20px;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 3px;
  }

  #tip input[type="button"] {
    height: 25px;
    color: #fff;
    font-size: 12px;
    line-height: 25px;
    text-align: center;
    background-color: #0d9bf2;
    border: 0;
    border-radius: 3px;
    outline: 0;
    cursor: pointer;
  }

  #tip input[type="text"] {
    height: 25px;
    padding-left: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
    outline: 0;
  }

  #pos {
    position: absolute;
    right: 7px;
    bottom: 28px;
    height: 70px;
    padding-right: 10px;
    padding-left: 10px;
    font-size: 12px;
    line-height: 30px;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 3px;
  }

  #pos input {
    height: 23px;
    border: 1px solid #ddd;
    border-radius: 3px;
    outline: 0;
  }

  #result1 {
    max-height: 300px;
  }

  .dot {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
  }
}
</style>